<template>
	<view>
		<view class="hbh_input">
			<view class="hbh_inputBox">
				<input v-model="value" :password="putType" :type="inpType" :maxlength="maxlength"
					:placeholder="placeholder">
				<view class="hbh_inpIcon" v-if="isSee" @click="changeIcon">
					<image :src="iconUrl" mode=""></image>
				</view>
				<view class="hbh_code" v-if="isCode" @click="sendCode" :style="{color:isSend?'#ccc':'#51C3FF'}">
					{{tip}}
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		sendCode
	} from "@/api/index.js"
	export default {
		name: "hbhInput",
		props: {
			isCode: { //是否是验证码框
				type: Boolean,
				default: false
			},
			placeholder: { //输入框提示词
				type: String
			},
			inpType: { //输入框类型
				type: String,
				default: "text"
			},
			maxlength: { //是否限制输入长度
				type: Number,
				default: -1
			},
			password: { //是否需要加密
				type: Boolean,
				default: false
			},
			isSee: { //是否是重要加密可控
				type: Boolean,
				default: false
			},
			defaultValue: {
				type: String || Number,
				default: ""
			},
			second: {
				type: Boolean,
				default: false
			}

		},
		data() {
			return {
				tip: "获取验证码",
				isSend: false,
				timer: null,
				value: "",
				isOpen: false,
				iconUrl: "/static/image/off.png",
				putType: this.password
			};
		},
		created() {
			this.value = this.defaultValue
		},
		watch: {
			value(newVal, oldVal) {
				this.$emit("sendValue", newVal)
			},
		},
		methods: {
			changeIcon() {
				if (this.isOpen) {
					this.iconUrl = "/static/image/off.png"
				} else {
					this.iconUrl = "/static/image/open.png"
				}
				this.isOpen = !this.isOpen
				this.putType = !this.putType
			},
			//发送验证码
			sendCode() {
				if (!this.second) {
					if (this.isSend) {
						uni.showToast({
							icon: "none",
							title: "不可频繁发送验证码"
						})
						return
					}
					sendCode().then((res) => {
						this.$emit("putCode", res.phoneCode)
						this.isSend = true
						var time = 60
						this.tip = time + '后可点击重新发送'
						this.timer = setInterval(() => {
							time--
							this.tip = time + '后可点击重新发送'
							if (time == 0) {
								this.tip = '获取验证码'
								this.isSend = false
								clearInterval(this.timer)
								this.timer = null
							}
						}, 1000)
					}).catch((err) => {
						uni.showToast({
							icon: "none",
							title: "验证码发送失败"
						})
						console.log(err)
					})
				} else {
					uni.showToast({
						icon: "none",
						title: "请先输入手机号"
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.hbh_input {
		height: 80rpx;
		border-bottom: 1rpx solid #F0F0F0;
		margin-bottom: 51rpx;

		.hbh_inputBox {
			height: 60rpx;
			display: flex;
			align-items: center;

			input {
				flex: 1;
				height: 60rpx;
				padding: 0rpx 20rpx;
				box-sizing: border-box;
			}

			.hbh_inpIcon {
				width: 40rpx;
				height: 40rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.hbh_code {
				font-size: 30rpx;
				font-weight: 400;
			}
		}

	}
</style>